import { ref, onMounted } from 'vue'
import {
  cancleOrder,
  deleteOrder,
  followOrUnfollow,
  getPrescriptionPic
} from '@/services/consult'
import type { ConsultOrderItem, FollowType } from '@/types/consult'
import { showFailToast, showImagePreview, showSuccessToast } from 'vant'
import { OrderType } from '@/enums'
import type { OrderDetail } from '@/types/order'
import { getMedicalOrderDetail } from '@/services/order'

export const useFollow = (type: FollowType = 'doc') => {
  const loading = ref(false)
  const follow = async (item: { id: string; likeFlag: 0 | 1 }) => {
    try {
      loading.value = true
      await followOrUnfollow(item.id, type)
      item.likeFlag = item.likeFlag === 1 ? 0 : 1
    } finally {
      loading.value = false
    }
  }

  return { loading, follow }
}

//查看处方
export const useShowPrescripition = () => {
  const showPrePic = async (id?: string) => {
    if (id) {
      const res = await getPrescriptionPic(id)
      showImagePreview([res.data.url])
    }
  }

  return { showPrePic }
}

//取消订单
export const useCancleOrder = () => {
  //取消订单
  const loading = ref(false)
  const cancelConsultOrder = async (item: ConsultOrderItem) => {
    try {
      loading.value = true
      await cancleOrder(item.id)
      item.status = OrderType.ConsultCancel
      item.statusValue = '已取消'
      showSuccessToast('取消成功')
    } catch (error) {
      showFailToast('取消失败')
    } finally {
      loading.value = false
    }
  }

  return { loading, cancelConsultOrder }
}

//删除订单
export const delOrder = (cb: () => void) => {
  const delLoading = ref(false)
  const deleteOrderByOrderId = async (item: ConsultOrderItem) => {
    try {
      delLoading.value = true
      await deleteOrder(item.id)
      showSuccessToast('删除成功')
      cb && cb()
    } catch (error) {
      showFailToast('删除失败')
    } finally {
      delLoading.value = false
    }
  }

  return { delLoading, deleteOrderByOrderId }
}

//获取药品订单详情
export const useMedicaldetail = (id: string) => {
  const loading = ref(false)
  const order = ref<OrderDetail>()
  //获取数据
  onMounted(async () => {
    loading.value = true
    try {
      const res = await getMedicalOrderDetail(id)
      order.value = res.data
    } finally {
      loading.value = false
    }
  })

  return { order, loading }
}
